<template>
  <div class="study-performance">
    <!-- 筛选区域 -->
    <div class="filter-container">
      <!-- 姓名搜索框 -->
      <div class="search-box">
        <input
          type="text"
          v-model="searchName"
          placeholder="输入姓名搜索..."
          class="search-input"
          @input="handleSearch"
        />
        <i class="el-icon-search search-icon"></i>
        <button
          v-if="searchName"
          class="clear-button"
          @click="clearSearch"
        >
          清除
        </button>
      </div>

      <div class="filter-group">
        <div class="filter-label">考试类型：</div>
        <div class="filter-options">
          <div
            v-for="type in examTypes"
            :key="type.value"
            class="filter-option"
            :class="{ active: selectedExamType === type.value }"
            @click="selectExamType(type.value)"
          >
            {{ type.label }}
          </div>
        </div>
      </div>

      <div class="filter-group">
        <div class="filter-label">专业筛选：</div>
        <div class="filter-options">
          <div
            v-for="major in majors"
            :key="major.value"
            class="filter-option"
            :class="{ active: selectedMajor === major.value }"
            @click="selectMajor(major.value)"
          >
            {{ major.label }}
          </div>
        </div>
      </div>

      <div class="filter-group">
        <div class="filter-label">科目筛选：</div>
        <div class="filter-options">
          <div
            v-for="subject in availableSubjects"
            :key="subject.value"
            class="filter-option"
            :class="{ active: selectedSubject === subject.value }"
            @click="selectSubject(subject.value)"
          >
            {{ subject.label }}
          </div>
        </div>
      </div>

      <div class="filter-group">
        <div class="filter-label">成绩筛选：</div>
        <div class="filter-options">
          <div
            v-for="grade in gradeRanges"
            :key="grade.value"
            class="filter-option"
            :class="{ active: selectedGradeRange === grade.value }"
            @click="selectGradeRange(grade.value)"
          >
            {{ grade.label }}
          </div>
        </div>
      </div>
    </div>

    <!-- 数据展示区域 -->
    <div class="data-container">
      <dv-border-box-12 class="content-box">
        <div class="content-wrapper">
          <div v-if="loading" class="loading-overlay">
            <i class="el-icon-loading"></i>
            <p>正在加载数据...</p>
          </div>

          <div v-else-if="filteredData.length === 0" class="no-data">
            <p v-if="searchName">没有找到名为 "{{ searchName }}" 的学生</p>
            <p v-else>没有符合条件的数据</p>
          </div>

          <div v-else class="data-table">
            <div class="table-header">
              <div class="table-cell rank-cell">排名</div>
              <div class="table-cell name-cell">姓名</div>
              <div class="table-cell class-cell">专业</div>
              <div class="table-cell exam-type-cell">考试类型</div>
              <div class="table-cell subject-cell">当前科目</div>
              <div class="table-cell score-cell">成绩</div>
              <div class="table-cell grade-cell">评分</div>
            </div>

            <div class="table-body custom-scrollbar">
              <div
                v-for="(item, index) in filteredData"
                :key="index"
                class="table-row"
                :class="getScoreClass(getSubjectScore(item), index)"
              >
                <div class="table-cell rank-cell">{{ index + 1 }}</div>
                <div class="table-cell name-cell">{{ item.name }}</div>
                <div class="table-cell class-cell">{{ item.major }}</div>
                <div class="table-cell exam-type-cell">{{ getExamTypeLabel(selectedExamType) }}</div>
                <div class="table-cell subject-cell">{{ getSubjectLabel(selectedSubject) }}</div>
                <div class="table-cell score-cell">{{ getSubjectScore(item) }}</div>
                <div class="table-cell grade-cell">{{ getGradeLabel(getSubjectScore(item), index) }}</div>
              </div>
            </div>
          </div>
        </div>
      </dv-border-box-12>
    </div>
  </div>
</template>

<script>
export default {
  name: 'StudyPerformance',
  data() {
    return {
      loading: true,
      searchName: '', // 姓名搜索关键词
      searchTimeout: null, // 搜索防抖动定时器
      // 筛选选项
      examInfo: [], // 存储从服务器获取的考试信息
      examTypes: [], // 动态生成的考试类型选项
      majors: [
        { label: '全部专业', value: 'all' },
        { label: '人工智能', value: '人工智能' },
        { label: '水声工程', value: '水声工程' },
        { label: '信息工程', value: '信息工程' },
        { label: '网电工程', value: '网电工程' },
        { label: '通信工程', value: '通信工程' },
        { label: '侦测工程', value: '侦测工程' }
      ],
      subjects: {}, // 动态生成的科目选项
      gradeRanges: [
        { label: '全部', value: 'all' },
        { label: '优秀(≥85)', value: 'excellent' },
        { label: '良好(≥75)', value: 'good' },
        { label: '及格(≥60)', value: 'pass' },
        { label: '不及格(<60)', value: 'fail' }
      ],

      // 当前选择
      selectedExamType: '',
      selectedMajor: 'all',
      selectedSubject: 'total',
      selectedGradeRange: 'all',

      // 数据
      studentData: [] // 存储从API获取的学生成绩数据
    };
  },
  computed: {
    availableSubjects() {
      return this.subjects[this.selectedExamType] || [];
    },
    filteredData() {
      let data = [...this.studentData];

      // 根据专业筛选
      if (this.selectedMajor !== 'all') {
        data = data.filter(item => item.major === this.selectedMajor);
      }

      // 根据姓名搜索
      if (this.searchName.trim()) {
        const searchTerm = this.searchName.trim().toLowerCase();
        data = data.filter(item => {
          return item.name.toLowerCase().includes(searchTerm);
        });
      }

      // 根据成绩范围筛选
      if (this.selectedGradeRange !== 'all') {
        data = data.filter(item => {
          const score = item.score;

          switch (this.selectedGradeRange) {
            case 'excellent':
              return score >= 85;
            case 'good':
              return score >= 75 && score < 85;
            case 'pass':
              return score >= 60 && score < 75;
            case 'fail':
              return score < 60;
            default:
              return true;
          }
        });
      }

      // 根据成绩排序
      data.sort((a, b) => b.score - a.score);

      return data;
    },

    // 学生成绩汇总数据，用于搜索结果展示
    studentSummary() {
      if (!this.searchName.trim()) return null;

      // 获取所有数据源
      const allData = {
        qimo: [...this.qimoData],
        yuekao: {
          rg: [...this.yuekaoData.rg],
          ss: [...this.yuekaoData.ss],
          xg: [...this.yuekaoData.xg]
        }
      };

      // 搜索学生
      const searchTerm = this.searchName.trim().toLowerCase();
      const student = {};

      // 搜索期末考试数据
      const qimoMatch = allData.qimo.find(item =>
        item.name.toLowerCase().includes(searchTerm)
      );
      if (qimoMatch) {
        student.qimo = qimoMatch;
      }

      // 搜索月考数据
      const rgMatch = allData.yuekao.rg.find(item =>
        item.name.toLowerCase().includes(searchTerm)
      );
      if (rgMatch) {
        student.yuekao = rgMatch;
      } else {
        const ssMatch = allData.yuekao.ss.find(item =>
          item.name.toLowerCase().includes(searchTerm)
        );
        if (ssMatch) {
          student.yuekao = ssMatch;
        } else {
          const xgMatch = allData.yuekao.xg.find(item =>
            item.name.toLowerCase().includes(searchTerm)
          );
          if (xgMatch) {
            student.yuekao = xgMatch;
          }
        }
      }

      return Object.keys(student).length > 0 ? student : null;
    }
  },
  mounted() {
    this.loadData();
  },
  methods: {
    async loadData() {
      this.loading = true;

      try {
        // 获取考试信息
        await this.fetchExamInfo();

        // 如果有考试信息，设置默认选中的考试类型
        if (this.examTypes.length > 0) {
          this.selectedExamType = this.examTypes[0].value;
          // 获取默认考试类型的学生成绩数据
          await this.fetchStudentData();
        }
      } catch (error) {
        console.error('加载数据出错:', error);
        this.$message.error('加载数据失败，请检查API连接');
      } finally {
        this.loading = false;
      }
    },

    // 获取考试信息
    async fetchExamInfo() {
      try {
        const result = await this.$overviewapi.getExamInfo();
        
        if (!result || !result.data || !Array.isArray(result.data)) {
          throw new Error('API返回数据格式不正确');
        }

        this.examInfo = result.data;

        // 生成考试类型选项
        const uniqueExamNames = [...new Set(result.data.map(item => item.examName))];
        this.examTypes = uniqueExamNames.map(name => ({
          label: name,
          value: name
        }));

        // 生成科目选项
        this.subjects = {};
        uniqueExamNames.forEach(examName => {
          const examSubjects = result.data
            .filter(item => item.examName === examName)
            .map(item => item.subject);
          
          // 为每个考试类型添加科目选项
          this.subjects[examName] = [
            { label: '总分', value: 'total' },
            ...examSubjects.map(subject => ({
              label: subject,
              value: subject.toLowerCase().replace(/\s+/g, '_')
            }))
          ];
        });
      } catch (error) {
        console.error('获取考试信息失败:', error);
        this.$message.error('获取考试信息失败，请检查API连接');
      }
    },

    // 获取学生成绩数据
    async fetchStudentData() {
      try {
        const result = await this.$overviewapi.getExamScore({
          examName: this.selectedExamType,
          subject: this.selectedSubject === 'total' ? "" : this.selectedSubject
        });

        if (!result || result.code !== '200' || !Array.isArray(result.data)) {
          throw new Error('API返回数据格式不正确');
        }

        // 格式化数据
        this.studentData = result.data.map(item => ({
          name: item.name || '',
          class: item.classes || '',
          major: item.major || '',
          group: item.groupName || '',
          score: Number(item.score) || 0,
          rank: Number(item.rank) || 0,
          examName: item.examName || '',
          examTime: item.examTime || ''
        }));

      } catch (error) {
        console.error('获取学生成绩数据失败:', error);
        this.$message.error('获取学生成绩数据失败，请检查API连接');
        this.studentData = [];
      }
    },

    // 修改选择考试类型的方法
    async selectExamType(type) {
      this.selectedExamType = type;
      // 重置科目选择为总分
      this.selectedSubject = 'total';
      // 重置专业选择
      this.selectedMajor = 'all';
      // 获取新的考试类型的学生成绩数据
      await this.fetchStudentData();
    },

    // 修改选择科目的方法
    async selectSubject(subject) {
      this.selectedSubject = subject;
      // 获取新的科目成绩数据
      await this.fetchStudentData();
    },

    // 修改选择专业的方法
    selectMajor(major) {
      this.selectedMajor = major;
    },

    // 修改选择成绩区间的方法
    selectGradeRange(grade) {
      this.selectedGradeRange = grade;
    },

    // 修改获取成绩的方法
    getSubjectScore(item) {
      if (!item) return 0;
      return item.score || 0;
    },

    getSubjectLabel(subjectValue) {
      const subject = this.availableSubjects.find(s => s.value === subjectValue);
      return subject ? subject.label : '';
    },

    getScoreClass(score, index) {
      // 如果当前科目是总分，根据排名百分比评分
      if (this.selectedSubject === 'total') {
        const totalCount = this.filteredData.length;
        if (totalCount === 0) return '';

        // 计算百分比位置
        const percentile = (index / totalCount) * 100;

        if (percentile <= 20) return 'excellent'; // 前20%
        if (percentile <= 50) return 'good'; // 前20%-50%
        if (percentile <= 80) return 'pass'; // 前50%-80%
        return 'fail'; // 后20%
      } else {
        // 其他科目仍然按照分数评分
        if (score >= 85) return 'excellent';
        if (score >= 75) return 'good';
        if (score >= 60) return 'pass';
        return 'fail';
      }
    },

    // 获取考试类型标签
    getExamTypeLabel(examType) {
      const examTypeObj = this.examTypes.find(type => type.value === examType);
      return examTypeObj ? examTypeObj.label : '';
    },

    // 获取评分标签
    getGradeLabel(score, index) {
      // 如果当前科目是总分，根据排名百分比评分
      if (this.selectedSubject === 'total') {
        const totalCount = this.filteredData.length;
        if (totalCount === 0) return '未知';

        // 计算百分比位置
        const percentile = (index / totalCount) * 100;

        if (percentile <= 20) return '优秀'; // 前20%
        if (percentile <= 50) return '良好'; // 前20%-50%
        if (percentile <= 80) return '及格'; // 前50%-80%
        return '不及格'; // 后20%
      } else {
        // 其他科目仍然按照分数评分
        if (score >= 85) return '优秀';
        if (score >= 75) return '良好';
        if (score >= 60) return '及格';
        return '不及格';
      }
    },

    // 姓名搜索相关方法
    handleSearch() {
      // 防抖动处理，避免频繁触发搜索
      if (this.searchTimeout) {
        clearTimeout(this.searchTimeout);
      }

      this.searchTimeout = setTimeout(() => {
        // 如果有搜索结果，展示学生所有考试成绩
        if (this.searchName.trim() && this.studentSummary) {
          // 如果学生有期末考试成绩，切换到期末考试模式
          if (this.studentSummary.qimo) {
            this.selectedExamType = 'qimo';
          }
          // 如果学生有月考成绩，切换到月考模式
          else if (this.studentSummary.yuekao) {
            this.selectedExamType = 'yuekao';
            // 切换到学生所在专业
            const major = this.studentSummary.yuekao.major;
            if (major.includes('人工')) {
              this.selectedMajor = 'rg';
            } else if (major.includes('水声')) {
              this.selectedMajor = 'ss';
            } else if (major.includes('信工')) {
              this.selectedMajor = 'xg';
            }
          }
        }
      }, 300);
    },

    clearSearch() {
      this.searchName = '';
      // 重置为默认筛选条件
      this.selectedExamType = this.examTypes[0]?.value || '';
      this.selectedMajor = 'all';
      this.selectedSubject = 'total';
      this.selectedGradeRange = 'all';
    }
  }
};
</script>

<style lang="scss" scoped>
/* 自定义滚动条样式 */
.custom-scrollbar {
  &::-webkit-scrollbar {
    width: 8px;
  }

  &::-webkit-scrollbar-track {
    background: rgba(19, 25, 47, 0.5);
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(104, 216, 254, 0.5);
    border-radius: 4px;
    border: 2px solid rgba(19, 25, 47, 0.5);
  }

  &::-webkit-scrollbar-thumb:hover {
    background-color: rgba(104, 216, 254, 0.7);
  }
}
.study-performance {
  width: 100%;
  height: 100%;
  color: #d3d6dd;

  .filter-container {
    background-color: rgba(19, 25, 47, 0.8);
    border-radius: 5px;
    padding: 15px;
    margin-bottom: 20px;
    border: 1px solid rgba(104, 216, 254, 0.3);

    /* 搜索框样式 */
    .search-box {
      display: flex;
      align-items: center;
      margin-bottom: 15px;
      position: relative;
      max-width: 400px;

      .search-input {
        flex: 1;
        background-color: rgba(19, 25, 47, 0.6);
        border: 1px solid rgba(104, 216, 254, 0.4);
        border-radius: 4px;
        color: #d3d6dd;
        padding: 8px 12px 8px 35px;
        font-size: 14px;
        outline: none;
        transition: all 0.3s;

        &:focus {
          border-color: rgba(104, 216, 254, 0.8);
          box-shadow: 0 0 5px rgba(104, 216, 254, 0.3);
        }

        &::placeholder {
          color: rgba(211, 214, 221, 0.5);
        }
      }

      .search-icon {
        position: absolute;
        left: 10px;
        color: rgba(104, 216, 254, 0.7);
        font-size: 16px;
      }

      .clear-button {
        margin-left: 10px;
        background-color: rgba(245, 108, 108, 0.2);
        border: 1px solid rgba(245, 108, 108, 0.4);
        color: #F56C6C;
        padding: 6px 12px;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          background-color: rgba(245, 108, 108, 0.3);
          border-color: rgba(245, 108, 108, 0.6);
        }
      }
    }

    .filter-group {
      display: flex;
      align-items: center;
      margin-bottom: 15px;

      &:last-child {
        margin-bottom: 0;
      }

      .filter-label {
        width: 100px;
        font-size: 16px;
        color: #68d8fe;
        font-weight: bold;
      }

      .filter-options {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;

        .filter-option {
          padding: 6px 12px;
          background-color: rgba(19, 25, 47, 0.6);
          border: 1px solid rgba(104, 216, 254, 0.3);
          border-radius: 4px;
          cursor: pointer;
          transition: all 0.3s;

          &:hover {
            background-color: rgba(104, 216, 254, 0.1);
          }

          &.active {
            background-color: rgba(104, 216, 254, 0.2);
            border-color: rgba(104, 216, 254, 0.8);
            color: #68d8fe;
            font-weight: bold;
          }
        }
      }
    }
  }

  .data-container {
    flex: 1;
    overflow: hidden;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;

    .content-box {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
    }

    .content-wrapper {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      position: relative;
      padding: 20px;
      box-sizing: border-box;
    }

    .loading-overlay {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      background-color: rgba(19, 25, 47, 0.8);
      z-index: 10;

      i {
        font-size: 40px;
        color: #68d8fe;
        margin-bottom: 20px;
      }

      p {
        font-size: 18px;
        color: #d3d6dd;
      }
    }

    .no-data {
      height: 100%;
      width: 100%;
      min-height: 300px;
      display: flex;
      justify-content: center;
      align-items: center;
      background: transparent;
      font-size: 18px;
      color: #d3d6dd;
      font-style: italic;
    }

    .data-table {
      flex: 1;
      min-height: 300px;
      display: flex;
      flex-direction: column;
      border: none;
      border-radius: 0;
      overflow: hidden;

      .table-header {
        display: flex;
        background-color: rgba(104, 216, 254, 0.1);
        border-bottom: 2px solid rgba(104, 216, 254, 0.5);
        padding: 12px 0;
        font-weight: bold;
        color: #68d8fe;
      }

      .table-body {
        flex: 1;
        overflow-y: auto;
        max-height: calc(100vh - 400px); /* 设置最大高度确保可滚动 */

        &::-webkit-scrollbar {
          width: 8px;
        }

        &::-webkit-scrollbar-track {
          background: rgba(19, 25, 47, 0.5);
          border-radius: 4px;
        }

        &::-webkit-scrollbar-thumb {
          background-color: rgba(104, 216, 254, 0.5);
          border-radius: 4px;
          border: 2px solid rgba(19, 25, 47, 0.5);
        }

        &::-webkit-scrollbar-thumb:hover {
          background-color: rgba(104, 216, 254, 0.7);
        }
      }

      .table-row {
        display: flex;
        border-bottom: 1px solid rgba(104, 216, 254, 0.2);
        padding: 10px 0;
        transition: background-color 0.3s;

        &:hover {
          background-color: rgba(104, 216, 254, 0.05);
        }

        &.excellent {
          background-color: rgba(103, 194, 58, 0.1);

          &:hover {
            background-color: rgba(103, 194, 58, 0.15);
          }

          .score-cell, .grade-cell {
            color: #67C23A;
            font-weight: bold;
          }
        }

        &.good {
          background-color: rgba(64, 158, 255, 0.1);

          &:hover {
            background-color: rgba(64, 158, 255, 0.15);
          }

          .score-cell, .grade-cell {
            color: #409EFF;
            font-weight: bold;
          }
        }

        &.pass {
          background-color: rgba(230, 162, 60, 0.1);

          &:hover {
            background-color: rgba(230, 162, 60, 0.15);
          }

          .score-cell, .grade-cell {
            color: #E6A23C;
            font-weight: bold;
          }
        }

        &.fail {
          background-color: rgba(245, 108, 108, 0.1);

          &:hover {
            background-color: rgba(245, 108, 108, 0.15);
          }

          .score-cell, .grade-cell {
            color: #F56C6C;
            font-weight: bold;
          }
        }
      }

      .table-cell {
        padding: 0 10px;
        display: flex;
        align-items: center;
      }

      .table-cell {
        flex: 1;
        justify-content: center;
        text-align: center;
      }

      .rank-cell {
        min-width: 60px;
      }

      .name-cell {
        min-width: 80px;
        justify-content: flex-start;
        text-align: left;
      }

      .class-cell {
        min-width: 100px;
        justify-content: flex-start;
        text-align: left;
      }

      .exam-type-cell {
        min-width: 100px;
      }

      .subject-cell {
        min-width: 100px;
      }

      .score-cell {
        min-width: 70px;
      }

      .grade-cell {
        min-width: 70px;
      }
    }
  }
}
</style>
